<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      table td {
        width: 100px;
        position: relative;
      }
      table td input {
        /* width: 100%; */
        /* position: absolute; */
        left: 0;
        right: 0;
        top: 0;
      }

      table .btns {
        background-color: antiquewhite;
      }

      table .btns button {
        width: 40px;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <table border="1">
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td data-cell>jack</td>
          <td data-cell>20</td>
          <td data-cell>boy</td>
        </tr>
        <tr>
          <td data-cell>lili</td>
          <td data-cell>20</td>
          <td data-cell>girl</td>
        </tr>
      </tbody>
    </table>
    <script>
      // 保存就内容
      const old = {
        cell: null,
        content: "",
      };
      document.onclick = (e) => {
        const html = String.raw;
        // 点击取消
        if (e.target.dataset.cancel !== undefined) {
          old.cell.innerText = old.conetnt;
          old.cell = null;
        }
        // 点击确定
        if (e.target.dataset.ok !== undefined) {
          old.cell.innerText = old.cell.querySelector("input").value;
          old.cell = null;
        }
        // 切换输入模式
        if (e.target.dataset.cell !== undefined && old.cell === null) {
          // 1 获取单元格的内容
          const cellContent = e.target.innerText;
          // 保存旧值和cell对象（方便后续操作）
          old.conetnt = cellContent;
          old.cell = e.target;

          // 2 创建输入框
          const input = html`<input
              data-editor
              onclick="event.stopPropagation()"
              type="text"
              value="${cellContent}"
            />
            <div class="btns">
              <button data-ok>确定</button>
              <button data-cancel>取消</button>
            </div> `;
          // 3 将输入框覆盖到box
          e.target.innerHTML = input;
          // 4 获取焦点
          e.target.querySelector("input").focus();
        }
      };
    </script>
  </body>
</html>
